package com.hmdp.controller;


import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
        //查询redis
        String key = RedisConstants.CACHE_SHOP_TYPE_KEY;
        Set typeSet = redisTemplate.opsForZSet().range(key, 0, -1);
        if (!typeSet.isEmpty()){
            //有缓存
            //存入shopTypeList中返回
            List<ShopType> shopTypeList = new ArrayList<>();

            for (Object obj :typeSet) {
                if(obj instanceof String){
                    //value-jsonStr 转实体类ShopType
                    ShopType shopType = JSONUtil.toBean((String) obj, ShopType.class);
                    shopTypeList.add(shopType);
                }
            }
            return Result.ok(shopTypeList);
        }
        //没缓存
        // 查询数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
        //缓存到redis
        for (ShopType shopType :typeList) {
            String jsonStr = JSONUtil.toJsonStr(shopType);
            redisTemplate.opsForZSet().add(key,jsonStr,shopType.getSort());
        }


        return Result.ok(typeList);
    }
}
